import request from '@/utils/request';
import { Session } from '@/utils/storage';
import { encryption } from '@/utils/crypto';

const AUTH_BASE_URL = '/api/v1/auth';
const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded';

const AuthAPI = {
  /** 登录接口*/
  login(data: any) {
    /*
      const formData = new FormData();
      formData.append("username", data.username);
      formData.append("password", data.password);
      formData.append("captchaKey", data.captchaKey);
      formData.append("captchaCode", data.captchaCode);
    */
    const basicAuth = 'Basic ' + window.btoa(import.meta.env.VITE_OAUTH2_PASSWORD_CLIENT);
    Session.set('basicAuth', basicAuth);
    let encPassword = data.password;
    // 密码加密
    if (import.meta.env.VITE_PWD_ENC_KEY) {
      encPassword = encryption(data.password, import.meta.env.VITE_PWD_ENC_KEY);
    }
    const params = {
      ...data,
      password: encPassword,
    };
    return request<any | LoginResult>({
      url: `/auth/oauth2/token`,
      method: 'post',
      data: params,
      headers: {
        skipToken: true,
        Authorization: basicAuth,
        'Content-Type': FORM_CONTENT_TYPE,
      },
      // headers: {
      //   "Content-Type": "multipart/form-data",
      // },
    });
  },

  /** 刷新 token 接口*/
  refreshToken(refreshToken: string) {
    return request<any, LoginResult>({
      url: `${AUTH_BASE_URL}/refresh-token`,
      method: 'post',
      params: { refreshToken: refreshToken },
      headers: {
        Authorization: 'no-auth',
      },
    });
  },

  /** 注销登录接口 */
  logout() {
    return request({
      url: `/auth/token/logout`,
      method: 'post',
    });
  },

  /** 获取验证码接口 (暂无)*/
  getCaptcha() {
    return request<any, CaptchaInfo>({
      url: `${AUTH_BASE_URL}/captcha`,
      method: 'get',
    });
  },
};

export default AuthAPI;

/** 登录表单数据 */
export interface LoginFormData {
  /** 用户名 */
  username: string;
  /** 密码 */
  password: string | null;
  /** 验证码缓存key */
  // captchaKey: string;
  /** 验证码 */
  // captchaCode: string;
  // 验证码
  code: string;
  /** 验证码随机数 */
  randomStr: string;
}

/** 登录响应 */
export interface LoginResult {
  /** 访问令牌 */
  accessToken: string;
  /** 刷新令牌 */
  refreshToken: string;
  /** 令牌类型 */
  tokenType: string;
  /** 过期时间(秒) */
  expiresIn: number;
}

/** 验证码信息 */
export interface CaptchaInfo {
  /** 验证码缓存key */
  captchaKey: string;
  /** 验证码图片Base64字符串 */
  captchaBase64: string;
}
